﻿using System;
using System.Data;
using System.Data.SqlClient;
using SMS.SMPPClient.PDU.Outgoing;
using WorkThreading;
using SMS.BLL;

namespace SMS.SMPPClient.Common
{
    public class MsgOutWorkItem : WorkItem
    {
        // Fields
        private int _contentType;
        private string _messageInfo;
        private int _msgOutID;
        private string _serviceID;
        private string _userID;
        private Gateway frmMain;
        private SMPPDataSM deliverSm = new SMPPDataSM();
        private SMPPSubmitSM submitSm;

        // Methods
        public MsgOutWorkItem(int MsgOutID, string UserID, string ServiceID, string MessageInfo, int ContentType)
        {
            this._msgOutID = MsgOutID;
            this._userID = UserID;
            this.deliverSm.DestAddress = this._userID;
            this._serviceID = ServiceID;
            this.deliverSm.SourceAddress = this._serviceID;
            this._messageInfo = MessageInfo;
            this._contentType = ContentType;
            this.deliverSm.SourceAddrTON = 1;
            this.deliverSm.SourceAddrNPI = 1;
            this.deliverSm.DestAddrTON = 1;
            this.deliverSm.DestAddrNPI = 1;
            this.deliverSm.RegisteredDelivery = new BitBuilder(1);
        }

        public override void Perform()
        {
            if (!this.frmMain.clientSoc.Connected)
            {
                this.UpdateStatus(2, "");
                throw new Exception("Cannot connect to SMSC");
            }
            
            if (this._serviceID.Length > 3)
                this._serviceID = this._serviceID.Substring(this.ServiceID.Length - 4);
            
            if (this._serviceID != "6198" && this._serviceID != "6298" && this._serviceID != "6398" && this._serviceID != "6498" && this._serviceID != "6598" && this._serviceID != "6698" && this._serviceID != "6798")
                throw new Exception("Invalid ServiceID = " + this._serviceID);

            try
            {
                switch (this.ContentType)
                {
                    case 0:
                        this.SendTextMsg();
                        goto gotoMark;

                    case 1:
                        this.SendRingtoneMsg();
                        goto gotoMark;

                    case 2:
                        this.SendLogoMsg();
                        goto gotoMark;

                    case 4:
                        this.SendPictureMsg();
                        goto gotoMark;

                    case 8:
                        if (this._messageInfo.ToLower().IndexOf(":http://") == -1)
                        {
                            this.UpdateStatus(3, "");
                            throw new Exception("MsgOutID = " + this._msgOutID.ToString() + " Wrong format WAPPUSH");
                        }
                        break;

                    default:
                        this.UpdateStatus(3, "");
                        throw new Exception("Wrong MsgOutID = " + this._msgOutID.ToString() + " ContentType");
                }
                this.SendPushMsg();

            gotoMark:
                if (this.deliverSm.CommandStatus == 0)
                {
                    this.UpdateStatus(9, this.deliverSm.ReceiptedMessageID);

                    if (ConfigApp.bLogMT)
                        this.frmMain.AddMsg(this, string.Concat(new object[] { "Send SMS from ", this._serviceID.ToString(), " to ", this._userID, " Content:", this._messageInfo, " - MessageId=", this.deliverSm.ReceiptedMessageID }));
                }
                else
                {
                    this.UpdateStatus(2, "");

                    if (ConfigApp.bLogMT)
                        this.frmMain.AddMsg(this, string.Concat(new object[] { "Sending error SMS from ", this._serviceID.ToString(), " to ", this._userID, " Content:", this._messageInfo, " - CommandStatus=", this.deliverSm.CommandStatus }));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private void SendLogoMsg()
        {
            string str2;
            string str = "06050415820000";

            if ((this._userID.Substring(0, 4) == "8490") || (this._userID.Substring(0, 4) == "8493"))
                str2 = "54F210";
            else
                str2 = "54F220";
            
            byte[] buffer = Utils.hex2bin(str + str2 + this._messageInfo);
            this.deliverSm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.deliverSm.ShortMessage.Value = buffer;
            this.deliverSm.EsmClass = new BitBuilder(0x40);
            this.submitSm = this.frmMain.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
        }

        private void SendPictureMsg()
        {
            string hex = "0B0504158A00000003010301" + this._messageInfo.Substring(0, 0xfe);
            string str2 = "0B0504158A00000003010302" + this._messageInfo.Substring(0xfe, 0xfe);
            string str3 = "0B0504158A00000003010303" + this._messageInfo.Substring(0x1fc, 0x12);
            
            byte[] buffer1 = Utils.hex2bin(hex);
            byte[] buffer2 = Utils.hex2bin(str2);
            byte[] buffer3 = Utils.hex2bin(str3);

            this.deliverSm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.deliverSm.ESMClass = new BitBuilder(0x40);
            
            this.deliverSm.ShortMessage.Value = buffer1;
            this.submitSm = this.frmMain.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
            
            this.deliverSm.ShortMessage.Value = buffer2;
            this.submitSm = this.frmMain.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
            
            this.deliverSm.ShortMessage.Value = buffer3;
            this.submitSm = this.frmMain.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
        }

        private void SendPushMsg()
        {
            string str1 = this._messageInfo;
            string text = str1.Substring(0, str1.ToLower().IndexOf(":http://"));
            
            PushMessage message = new PushMessage(str1.Substring(text.Length + 1, (str1.Length - text.Length) - 1), text);
            HexDecoder decoder = new HexDecoder();

            string str2 = new string(decoder.GetChars(message.GetSMSBytes()));
            string[] strArr1 = Utils.SplitMessage(str2.Substring(14, str2.Length - 14));
            byte[][] bufferArr = new byte[strArr1.Length][];

            if (strArr1.Length == 1)
            {
                strArr1[0] = "0605040B8423F0" + strArr1[0];
                bufferArr[0] = Utils.hex2bin(strArr1[0]);
            }
            else
            {
                for (int j = 0; j < strArr1.Length; j++)
                {
                    string[] strArr2 = new string[] { "0B05040B8423F00003010", strArr1.Length.ToString(), "0", (j + 1).ToString(), strArr1[j] };
                    strArr1[j] = string.Concat(strArr2);
                    bufferArr[j] = Utils.hex2bin(strArr1[j]);
                }
            }

            this.deliverSm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.deliverSm.EsmClass = new BitBuilder(0x40);

            for (int i = 0; i < strArr1.Length; i++)
            {
                this.deliverSm.ShortMessage.Value = bufferArr[i];
                this.submitSm = this.frmMain.SubmitSm(new SmppSubmitSmReq(this.deliverSm));
            }
        }

        private void SendRingtoneMsg()
        {
            string[] strArr1 = Utils.SplitMessage(this._messageInfo);
            byte[][] bufferArr = new byte[strArr1.Length][];

            for (int i = 0; i < strArr1.Length; i++)
            {
                string[] strArr2 = new string[] { "0B0504158115810003AA0", strArr1.Length.ToString(), "0", (i + 1).ToString(), strArr1[i] };
                strArr1[i] = string.Concat(strArr2);
                bufferArr[i] = Utils.hex2bin(strArr1[i]);
            }
            
            this.deliverSm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.deliverSm.ESMClass = new BitBuilder(0x40);
            
            for (int j = 0; j < strArr1.Length; j++)
            {
                this.deliverSm.ShortMessage.Value = bufferArr[j];
                this.submitSm = this.frmMain.SubmitSm(new SmppSubmitSmReq(this.deliverSm));
            }
            if (ConfigApp.bLogMT)
            {
                string str1 = "";
                for (int k = 0; k < strArr1.Length; k++)
                {
                    string str2 = str1;
                    string[] strArr3 = new string[] { str2, "\r\nMsg ", (k + 1).ToString(), " : ", strArr1[k] };
                    str1 = string.Concat(strArr3);
                }
                
                if (this.deliverSm.CommandStatus == 0)
                    this.frmMain.WriteLog("Send MsgOut Ringtone successfully - From " + this._serviceID + " To " + this._userID + str1);
                else
                    this.frmMain.WriteLog("Send MsgOut Ringtone failed - From " + this._serviceID + " To " + this._userID + str1);
            }
        }

        private void SendTextMsg()
        {
            if (this._messageInfo.Length > 160)
                this._messageInfo = this._messageInfo.Substring(0, 160);
            
            this.deliverSm.ShortMessage.SetValue(this._messageInfo, SmppDataCoding.Default);
            this.submitSm = this.frmMain.SubmitSm(new SmppSubmitSmReq(this.deliverSm));
        }

        private void UpdateStatus(int Status, string MessageID)
        {
            string connStr = ConfigApp.ConnStr;
            string _servid = "";

            if (this._serviceID == "6198") _servid = "81";
            else if (this._serviceID == "6298") _servid = "82";
            else if (this._serviceID == "6398") _servid = "83";
            else if (this._serviceID == "6498") _servid = "84";
            else if (this._serviceID == "6598") _servid = "85";
            else if (this._serviceID == "6698") _servid = "86";
            else if (this._serviceID == "6798") _servid = "87";

            string cmdText = ("UPDATE MsgOut_" + _servid + " SET Status=@Status,MessageID=@MessageID,ResponseTime=getdate() ") + " WHERE MsgOutID=@MsgOutID";
            
            SqlConnection cnn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(cmdText, cnn);
            cmd.Parameters.Clear();
            
            SqlParameter param1 = new SqlParameter("@Status", SqlDbType.Int);
            param1.Value = Status;
            cmd.Parameters.Add(param1);
            
            SqlParameter param2 = new SqlParameter("@MessageID", SqlDbType.VarChar, 50);
            param2.Value = MessageID;
            cmd.Parameters.Add(param2);
            
            SqlParameter param3 = new SqlParameter("@MsgOutID", SqlDbType.BigInt);
            param3.Value = this._msgOutID;
            cmd.Parameters.Add(param3);
            
            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();
        }

        // Properties
        public int ContentType
        {
            get { return this._contentType; }
            set { this._contentType = value; }
        }

        public string MessageInfo
        {
            get { return this._messageInfo; }
            set { this._messageInfo = value; }
        }

        public int MsgOutID
        {
            get { return this._msgOutID; }
            set { this._msgOutID = value; }
        }

        public string ServiceID
        {
            get { return this._serviceID; }
            set { this._serviceID = value; }
        }

        public string UserID
        {
            get { return this._userID; }
            set { this._userID = value; }
        }
    }
}

